const constants = require('../data/constants.js');
const fs        = require('fs');
const nodeSchedule  = require('node-schedule');
const cameraModel   = require('../model/device');
const channelModel   = require('../model/channel');

let mySchedule;

/**
 * 计划任务
 */
let Schedule={
    /**
     * 开启定时器
     */
    start:function(){
        const interval= '30 * * * * *';
        const me = this;
        console.info('开启计划任务:', interval);
        mySchedule = nodeSchedule.scheduleJob(interval,function(){
            // zlk日志
            console.log('scheduleCronstyle:'+new Date());
            let path = 'ZLMediaKit/log/';
            // zlk ffmpeg日志
            me.checkLog(path,constants.logger.filecount );
            path = 'ZLMediaKit/ffmpeg/';
            me.checkLog(path,constants.logger.filecount );
            // gb28181 log4js的日志
            path = constants.logger.path ;
            me.checkLog(path,constants.logger.filecount,/^request(.*)\.log$/ );
            me.checkLog(path,constants.logger.filecount,/^error(.*)\.log$/ );
            me.checkLog(path,constants.logger.filecount,/^info(.*)\.log$/ );

            // 定时检查有没有通道离线了
            cameraModel.reset();
            channelModel.reset();
        });
    },
    /**
     * 取消定时器
     */
    stop:function(){
        if(mySchedule){
            mySchedule.cancel();
        }
    },
    /**
     * path 路径
     * count 留几个
     * pattern 文件名匹配正则表达式
     */
    checkLog(path,count,pattern){
        if(path.charAt(path.length-1)!='/') path+='/';
        console.log('检查目录', path);
        fs.readdir(path,function(err,files){
            if(err){
              console.error(err);
              return;
            }
            var files = fs.readdirSync(path)
                  .map(function(v) { 
                      let stat=fs.statSync(path + v);
                    //   console.log('文件stat',stat);
                      return { name:v,
                               time:stat.ctime.getTime()
                             }; 
                   })
                   .sort(function(a, b) { return a.time - b.time; })
                   .map(function(v) { return v.name; });

            if(pattern){
                files = files.filter(x=>pattern.test(x));
            }

            if(files.length>5){
                for(var i =0; i<files.length-5; i++){
                    let tmp = path + files[i];
                    fs.unlink(path+files[i],(err)=>{
                        if(err){
                            console.error(err);
                            return false;
                        }else{
                            console.log('删除成功',tmp);
                        }
                    })
                }
            }
            
          });
    }
};

module.exports=Schedule;